package com.landeb.shop.huo.frag;

import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.landeb.shop.R;
import com.landeb.shop.huo.BannerLoader;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.act.ShopListActivity;
import com.landeb.shop.huo.adapter.FragGoodBottomSheetLVAdapter;
import com.landeb.shop.huo.bean.BeanFragGood;
import com.landeb.shop.huo.bean.BeanFragGoodAddressLV;
import com.landeb.shop.huo.eventMsg.MsgResetGoodsFrag;
import com.landeb.shop.huo.httpRequest.FragGoodRequest;
import com.youth.banner.Banner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class GoodFragActGoodDetail extends Fragment implements View.OnClickListener {

    private View view;

    private static final String BASE_URL = "baseUrl";
    private String mID;
    private String mTitle;
    private String mPrice;
    private String mBaseUrl;
    public static String mShopId;

    private SwipeRefreshLayout mSRL;
    private Banner mBanner;
    private TextView tvTitle, tvDesc, tvPrice, tvAddress;
    private LinearLayout llAddressPicker;

    private ImageView ivLogo;
    private TextView tvShopName, tvShopFocus, tvShopGoods;


    private List<String> mBannerUrlList = new ArrayList<>();

    private String mUrl;
    private Retrofit mRetrofit;
    private FragGoodRequest mRequest;
    private boolean isRefreshing = false;

    public static GoodFragActGoodDetail newInstance(String baseUrl) {
        GoodFragActGoodDetail fragment = new GoodFragActGoodDetail();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        fragment.setArguments(args);
        return fragment;
    }

    public static GoodFragActGoodDetail newInstance(String baseUrl, String id, String title, String price) {
        GoodFragActGoodDetail fragment = new GoodFragActGoodDetail();
        Bundle args = new Bundle();
        args.putString(BASE_URL, baseUrl);
        args.putString("id", id);
        args.putString("title", title);
        args.putString("price", price);
        fragment.setArguments(args);
        return fragment;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReset(MsgResetGoodsFrag event) {

        mID= event.getMid();

        refresh();
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);


        mBaseUrl = getArguments().getString(BASE_URL);
        mID = getArguments().getString("id");
        mTitle = getArguments().getString("title");
        mPrice = getArguments().getString("price");

        OkHttpClient client = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        mRequest = mRetrofit.create(FragGoodRequest.class);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_good_frag_act_good_detail, container, false);

//        Log.e("onCreateView: ", mID + mTitle + mPrice);

//        Toast.makeText(getActivity(), mID + mTitle + mPrice, Toast.LENGTH_SHORT).show();


        initView();
        initData();
        initEvent();

        refresh();
        return view;
    }

    private void initEvent() {

        mSRL.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        mSRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mBanner.setImages(mBannerUrlList);
        mBanner.setImageLoader(new BannerLoader());
        mBanner.isAutoPlay(false);
        mBanner.start();
//        mBanner.start().stopAutoPlay();
        llAddressPicker.setOnClickListener(this);
    }

    private void initData() {

    }

    private void initView() {

        mSRL = (SwipeRefreshLayout) view.findViewById(R.id.frag_good_srl);
        mBanner = (Banner) view.findViewById(R.id.frag_good_banner);

        tvTitle = (TextView) view.findViewById(R.id.frag_good_tv_title);
        tvDesc = (TextView) view.findViewById(R.id.frag_good_tv_desc);
        tvPrice = (TextView) view.findViewById(R.id.frag_good_tv_price);

        tvAddress = (TextView) view.findViewById(R.id.frag_good_tv_address);
        llAddressPicker = (LinearLayout) view.findViewById(R.id.frag_good_ll_address_picker);

        if (TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mPrice)) {

            tvTitle.setText(mTitle);
            tvPrice.setText("¥" + mPrice);
        }

        ivLogo = (ImageView) view.findViewById(R.id.frag_good_iv_logo);
        tvShopName = (TextView) view.findViewById(R.id.frag_good_tv_shopName);
        tvShopFocus = (TextView) view.findViewById(R.id.frag_good_tv_shopFocusCount);
        tvShopGoods = (TextView) view.findViewById(R.id.frag_good_tv_shopGoodsCount);

    }

    private void refresh() {

        if (!isRefreshing) {
            isRefreshing = true;

            mRequest.getGoodDetail(mID)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BeanFragGood>() {
                        @Override
                        public void onCompleted() {
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                            Log.e("getGoodDetail", "onCompleted: ");
                        }

                        @Override
                        public void onError(Throwable e) {
                            isRefreshing = false;
                            mSRL.setRefreshing(false);
                            Log.e("getGoodDetail", "onError: " + e.toString());

                        }

                        @Override
                        public void onNext(BeanFragGood beanFragGood) {

                            if (beanFragGood.getStatus() == 1) {

                                BeanFragGood.DataBean data = beanFragGood.getData();
                                //轮播图赋值
                                mBannerUrlList.clear();
                                mBanner.setImages(mBannerUrlList);

                                for (int i = 0; i < data.getImages().size(); i++) {
                                    mBannerUrlList.add(data.getImages().get(i).getUrl());
                                }

                                Log.e("imgs ",mBannerUrlList.size()+"" );

                                mBanner.setImages(mBannerUrlList);
                                mBanner.start().startAutoPlay();
//                                mBanner.start().stopAutoPlay();

                                tvTitle.setText(data.getName());//标题赋值
                                tvDesc.setText(data.getSubname());//赋值描述
                                tvPrice.setText("¥" + data.getPrice());//赋值价格

                                mShopId = data.getStore_id();//获取shopid

                                Glide.with(getActivity()).load(data.getStore_logo()).into(ivLogo);

                                tvShopName.setText(data.getStorename());
                                tvShopFocus.setText(data.getStore_favorite());
                                tvShopGoods.setText(data.getStore_goods());

                            } else {
                                Toast.makeText(getActivity(), beanFragGood.getInfo(), Toast.LENGTH_SHORT).show();
                            }


                        }
                    });
        }

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.frag_good_ll_address_picker:
                // TODO: 2016/11/20 点击选择地址

                mRequest.getAddress()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanFragGoodAddressLV>() {
                            @Override
                            public void onCompleted() {
                                Log.e("getAddress", "onCompleted: ");
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("getAddress", "onError: " + e.toString());

                            }

                            @Override
                            public void onNext(BeanFragGoodAddressLV beanFragGoodAddressLV) {

                                if (beanFragGoodAddressLV.getStatus() == 1) {

                                    final BottomSheetDialog dialog = new BottomSheetDialog(getActivity());

                                    View dialogView = LayoutInflater.from(getActivity()).inflate(R.layout.frag_good_bottom_sheet_lv, null);
                                    ListView listView = (ListView) dialogView.findViewById(R.id.frag_good_lv_bottom_sheet);
//                                    final String[] array = new String[]{"item_score_log_act_rv-1", "item_score_log_act_rv-2", "item_score_log_act_rv-3", "item_score_log_act_rv-4", "item_score_log_act_rv-5", "item_score_log_act_rv-6", "item_score_log_act_rv-7", "item_score_log_act_rv-8", "item_score_log_act_rv-9", "item_score_log_act_rv-11", "item_score_log_act_rv-12", "item_score_log_act_rv-13", "item_score_log_act_rv-14", "item_score_log_act_rv-15", "item_score_log_act_rv-16", "item_score_log_act_rv-71", "item_score_log_act_rv-18", "item_score_log_act_rv-19"};
//                                    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, array);
                                    final List<BeanFragGoodAddressLV.DataBean> mAddresses = new ArrayList<BeanFragGoodAddressLV.DataBean>();
                                    mAddresses.addAll(beanFragGoodAddressLV.getData());

                                    FragGoodBottomSheetLVAdapter mAdapter = new FragGoodBottomSheetLVAdapter(getActivity(), mAddresses);
                                    listView.setAdapter(mAdapter);
                                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                                            Toast.makeText(getActivity(), mAddresses.get(i).getAddress(), Toast.LENGTH_SHORT).show();
                                            // TODO: 2016/11/22 选择地址后的逻辑
                                            tvAddress.setText(mAddresses.get(i).getAddress());
                                            dialog.dismiss();
                                        }
                                    });
                                    dialog.setContentView(dialogView);
                                    dialog.show();


                                } else {
                                    Toast.makeText(getActivity(), beanFragGoodAddressLV.getInfo(), Toast.LENGTH_SHORT).show();
                                }


                            }
                        });





                break;
        }
    }


//    @Override
//    public void onStart() {
//        super.onStart();
//    }


//    @Override
//    public void onStop() {
//        super.onStop();
//        EventBus.getDefault().unregister(this);
//    }



    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }
}
